(function (method) {
  method(window, window.document, jQuery);
})(function (win, doc, $) {
  //点击显示 时分秒（hh:mm:ss）格式
  // jeDate("#texthms", {
  //     isinitVal: true,
  //     format: "hh:mm:ss"
  // });
  /**
   * options {obj} 需要传的值
   * domId dom结构的id
   * timeList  时间轴的数组对象 例如：[{label: '00:00', value: 0}]
   *
   * videoTime {string} 视频时长 例如：10:35:00
   *
   * callback {function} 实时接收返回数据
   *
   * downloadFun {function} 下载视频的回调方法
   */
  //  需要返回的对象
  var dataDate = {};
  // 时间段的参数
  var time1,
    time2,
    defaultTime1,
    defaultTime2,
    timeValue1,
    timeValue2,
    downloadTimeStart,
    downloadTimeEnd,
    downloadRangeLeft,
    downloadRangeWidth;
  // 时间轴的参数
  var timeSlideInnerWidthInit,
    timeSlideInnerLeft,
    flagOffsetBeginLeft,
    flagOffsetEndLeft,
    currentDate,
    currentTime,
    videoWidth,
    isdbClickDownloadRange = false,
    downloadX,
    isDownloadRange,
    loadMax = 0;
  $.fn.moly_DragTimeline = function (options, callback, downloadFun) {
    var DOM = window.document.getElementById(options.domId);
    DOM.style.boxSizing = "border-box";
    $("#" + options.domId).empty();
    var timeList = options.timeList;
    var html = "";
    for (var index = 0; index < timeList.length; index++) {
      var element = timeList[index];
      html +=
        '<li class="time-item ' +
        index +
        '" disabled style="list-style: none;width: 60px;" ><span class="sso ' +
        index +
        '" style="margin-left: -14px;">' +
        timeList[index].label +
        "</span></li>";
    }

    DOM.innerHTML =
      '<div class="time-slider-con"><div class="time-grid-con" onselectstart="return false;"><ul class="time-slide-inner" style="left: 0px; margin-left: 16px;">' +
      html +
      "</ul></div></div>";

    var ULDOM = window.document.getElementsByClassName("time-grid-con")[0];
    ULDOM.style.height = "40px";
    ULDOM.style.lineHeight = "40px";
    ULDOM.style.width = "100%";
    ULDOM.style.position = "relative";
    ULDOM.style.overflow = "hidden";
    ULDOM.style.borderTop = "1px solid #6e6e6e";
    ULDOM.style.borderBottom = "1px solid #6e6e6e";
    ULDOM.style.background = options.timeLineBackground
      ? options.timeLineBackground
      : "#6e6e6e";

    $(".time-slider-con").append(
      '<div  onselectstart="return false;" class="time-flag" style="left:16px"><span class="flag"><style>.flag{position: relative;display: inline-block;width: 1px;height: 54px;background: #ffbe00;}.time-flag{position: absolute;top: -12px;z-index: 99;cursor: move;font-size: 12px;}.text{position: absolute;top: -20px; white-space: nowrap;padding: 0 14px;height: 24px;line-height: 24px;border-radius: 16px;text-align: center;font-size: 12px;color: #fff;background: #ff9a02;left: -16px;}</style></span><span id="text" class="text">2021-09-24  00:00</span></div>'
    );
    $(".time-slide-inner").append(
      '<li class="download-range" style="left: 384px; width: 10px; display: none;top: 0"><style>.download-range{position: absolute;bottom: 4px;left: 0; width: 5px;height: 42px;z-index: -1;background: #39c160;cursor: e-resize;}</style></li>'
    );

    // 黄色区域
    var colorTips = "";
    for (var index = 0; index < options.videoTime.length; index++) {
      var element = options.videoTime[index];
      colorTips +=
        '<li class="color-tips" style="width:' +
        ($.adapterTime(element.end) - $.adapterTime(element.start)) +
        "px;position: absolute; top: 0px; bottom: 0px; left: " +
        $.adapterTime(element.start) +
        'px; z-index: -2;"></li>';
    }
    $(".time-slide-inner").append(colorTips);
    $(".color-tips").css({
      width: videoWidth,
      background: options.downloadLineBackground || "rgb(255, 154, 2)",
    });
    $(".download-range").css({
      background: options.selectedDownloadLineBackground || "rgb(255, 154, 2)",
    });
    $(".text").css({ background: options.tipTextBackground || "#ff9a02" });
    $(".flag").css({ background: options.tipTextBackground || "#ff9a02" });

    $(".time-slide-inner").append(
      "<style>.time-slide-inner{position: absolute;top: 0;margin: 0;padding: 0;font-size: 0;cursor: pointer;z-index: 9;}</style >"
    );
    $(".time-item").append(
      '<style>.time-item{position: relative;display: inline-block;-webkit-box-sizing: border-box;box-sizing: border-box;height: 100%;text-align: left;font-size: 12px;} .time-item::before{content: " ";position: absolute; left: 0;bottom: 0; width: 1px;height: 8px;background: #d0d0d0;}</style >'
    );

    // 时间控件
    var timeDom =
      '<div class="downloadTime"><div class="timeTip">提示</div><div class="timeBox"><div class="downloadTip">下载时间：<span>' +
      options.downloadTipText +
      '</span></div><input class="dateinput dateicon mr25" id="datetimepicker_1" style="height: 30px;font-size: 14px;width: 120px;" type="text" placeholder="开始时间" placeholder="" readonly> - <input placeholder="结束时间" class="dateinput dateicon mr25" id="datetimepicker_2" style="height: 30px;width: 120px;font-size: 14px;" type="text" placeholder="" readonly></div><div class="btn"><div class="downloadBtn">下载</div><div class="cancelBtn">取消</div></div></div>';
    $("#" + options.domId).append(timeDom);
    $("#" + options.domId).append(
      '<div class="message">选择的时间不规范，开始时间大于结束时间，已为您清空，请重新选择</div>'
    );

    $(".downloadTime").css({
      boxShadow: "2px 2px 6px #888888",
      borderRadius: "5px",
      position: "fixed",
      top: "5px",
      left: "50%",
      transform: "translateX(-50%)",
      background: "#05172c",
      width: "400px",
      textAlign: "center",
      paddingBottom: "5px",
      display: "none",
    });

    $(".message").css({
      display: "none",
      borderRadius: "5px",
      position: "fixed",
      top: "-50px",
      left: "50%",
      transform: "translateX(-50%)",
      background: "#fdf6ec",
      textAlign: "center",
      paddingBottom: "5px",
      color: "#e6a23c",
      padding: "10px 15px",
      border: "#fcf4e8 1px solid",
      zIndex: 1000,
    });

    $(".downloadTip").css({
      lineHeight: "40px",
      fontSize: "13px",
      textAlign: "left",
      textIndent: "4em",
    });

    $(".timeTip").css({
      lineHeight: "30px",
      height: "30px",
      color: "#FFF",
      fontSize: "18px",
      textAlign: "left",
      borderBottom: "1px solid #3C78A8",
      padding: "3px 10px",
    });

    $(".timeBox").css({
      // lineHeight: "60px",
      // height: "60px",
      color: "#fff",
    });

    $(".dateinput").css({
      borderRadius: "5px",
      border: "1px solid #dcdfe6",
      color: "#fff",
      background: "#0F2966",
      border: "1px solid #0F2966",
      padding: "0 10px",
    });

    $(".btn").css({
      display: "inline-block",
      // lineHeight: "30px",
      // height: "40px",
      fontSize: "14px",
      textAlign: "left",
      padding: "5px 10px",
      margin: "0 auto",
      marginTop: "15px",
    });

    $(".btn div").css({
      cursor: "pointer",
      display: "inline-block",
      width: "70px",
      textAlign: "center",
      // float: "right",
      marginLeft: "10px",
      borderRadius: "5px",
      padding: "10px",
      color: "#FFFFFF",
      background: "#085D82",
    });

    // $(".btn .downloadBtn").css({
    //   background: "#2079fb",
    //   color: "#fff",
    // });

    timeSlideInnerLeft = $(".time-slide-inner")[0].offsetLeft;
    var aInt =
      $(".time-slider-con").width() -
      $(".time-slide-inner").width() -
      timeSlideInnerLeft;
    flagOffsetBeginLeft = $(".time-flag")[0].offsetLeft;
    timeSlideInnerWidthInit = $(".time-slide-inner").width();
    // 默认值
    currentDate = options.downloadTipText;
    $("#text").text(currentDate + "   " + "00:00");

    // 修改标点的样式
    $.changeFlagStyle(options);
    
    // 拖拽事件方法
    $.drag(options, callback);

    // 视频下载事件
    $.downloadRange(options, callback);

    // 注册点击事件
    $(".downloadBtn").click(function () {
      downloadFun({ start: time1, end: time2 });
    });

    $(".cancelBtn").click(function () {
      $("#datetimepicker_1").val("");
      $("#datetimepicker_2").val("");
      $(".download-range").css({ width: 0 });

      // 时间选择框的显示与隐藏
      $(".downloadTime").animate({ top: "-50px" });
      $(".downloadTime").css({
        display: "none",
      });
      isdbClickDownloadRange = false;
    });
  };

  $.changeFlagStyle = function (options) {
    var isTrueArr = [];
    for (var index = 0; index < options.videoTime.length; index++) {
      var element = options.videoTime[index];
      start1 = $.adapterTime(element.start);
      end1 = $.adapterTime(element.end);

      isTrueArr.push(
        start1 <= flagX - timeSlideInnerLeft + Math.abs(sliderX) &&
          flagX - timeSlideInnerLeft + Math.abs(sliderX) <= end1
      );
    }

    // 修改样式
    if (isTrueArr.indexOf(true) != -1) {
      $(".text").css({
        background: options.tipTextBackground || "#ff9a02",
      });
      $(".flag").css({
        background: options.tipTextBackground || "#ff9a02",
      });
    } else {
      $(".text").css({ background: "#d0d0d0" });
      $(".flag").css({ background: "#d0d0d0" });
    }
  };
  // 双击下载方法
  $.downloadRange = function (options) {
    var isTrueArr = [],
      start1,
      end1,
      timeWidth;
    $(".time-slide-inner").dblclick(function (e) {
      isTrueArr = [];
      maxLeft = 0;
      var clickPosition = Number(e.target.classList[1]) * 60 + e.offsetX;
      for (var index = 0; index < options.videoTime.length; index++) {
        var element = options.videoTime[index];
        start1 = $.adapterTime(element.start);
        end1 = $.adapterTime(element.end);
        isTrueArr.push(start1 < clickPosition && clickPosition < end1);
        if (start1 < clickPosition && clickPosition < end1) {
          timeWidth = element;
        }
      }

      if (isTrueArr.indexOf(true) == -1) {
        // 提示框的显示与隐藏
        $(".message").text("该时间段不支持下载");
        $(".message").css({
          display: "block",
          zIndex: 999,
        });
        $(".message").animate({ top: "5px" });
        var timeOutId = setTimeout(function () {
          $(".message").animate({ top: "-50px" });
          $(".message").css({
            display: "none",
          });
          timeOutId = "";
        }, 3000);
      } else {
        // 显示时间选择框
        $(".downloadTime").css({
          display: "block",
          zIndex: 999,
        });
        isdbClickDownloadRange = true;
        $(".downloadTime").animate({ top: "5px" });
        downloadRangeLeft = clickPosition - maxLeft;

        for (var index = 0; index < options.videoTime.length; index++) {
          var element = options.videoTime[index];
          start1 = $.adapterTime(element.start);
          end1 = $.adapterTime(element.end);

          if (start1 <= downloadRangeLeft && downloadRangeLeft <= end1) {
            loadMax = end1;
          }
        }

        $(".download-range").css({
          display: "block",
          left: downloadRangeLeft,
          width: "10px",
        });
        downloadTimeStart = $.zeroize(clickPosition);
        downloadTimeEnd = $.zeroize(
          clickPosition + $(".download-range").width()
        );
        // 时间控件的方法
        $.getTimeControl(timeWidth);
      }
    });
  };

  $.getTimeControl = function (videoTime) {
    defaultTime1 = downloadTimeStart.split(":");
    defaultTime2 = downloadTimeEnd.split(":");

    time1 = downloadTimeStart + ":00";
    time2 = downloadTimeEnd + ":00";
    timeValue1 = $.adapterTime(downloadTimeStart);
    timeValue2 = $.adapterTime(downloadTimeEnd);
    //点击显示 时分秒（hh:mm:ss）格式
    jeDate("#datetimepicker_1", {
      isinitVal: true,
      initDate: [{ hh: defaultTime1[0], mm: defaultTime1[1], ss: 00 }, false],
      format: "hh:mm:ss",
      isToday: false,
      isClear: false,
      minDate: videoTime.start.split(":")[0] + ":" + "00",
      maxDate: videoTime.end.split(":")[0] + ":" + 59,
      donefun: function (obj) {
        time1 = obj.val;
        timeValue1 = $.adapterTime(time1);
        if (timeValue1 > timeValue2 && timeValue2 != 0) {
          $("#datetimepicker_1").val("");
          $("#datetimepicker_2").val("");
          time1 = "";
          timeValue1 = 0;
          time2 = "";
          timeValue2 = 0;

          // 提示框的显示与隐藏
          $(".message").css({
            display: "block",
          });
          $(".message").animate({ top: "5px" });
          // 隐藏可下载部分颜色
          $(".download-range").css({ display: "none" });

          var timeOutId = setTimeout(function () {
            $(".message").animate({ top: "-50px" });
            $(".message").css({
              display: "none",
            });

            timeOutId = "";
          }, 3000);
        } else {
          $(".download-range").css({
            display: "block",
            left: timeValue1,
            width: timeValue2 - timeValue1,
          });
        }
      },
    });

    jeDate("#datetimepicker_2", {
      isinitVal: true,
      initDate: [{ hh: defaultTime2[0], mm: defaultTime2[1], ss: 00 }, false],
      format: "hh:mm:ss",
      isToday: false,
      isClear: false,
      minDate: videoTime.start.split(":")[0] + ":" + "00",
      maxDate: videoTime.end.split(":")[0] + ":" + 59,
      donefun: function (obj) {
        time2 = obj.val;
        timeValue2 = $.adapterTime(time2);

        if (timeValue1 != 0) {
          if (timeValue1 > timeValue2) {
            $("#datetimepicker_1").val("");
            $("#datetimepicker_2").val("");
            time1 = "";
            timeValue1 = 0;
            time2 = "";
            timeValue2 = 0;

            // 提示框的显示与隐藏
            $(".message").css({
              display: "block",
            });
            $(".message").animate({ top: "5px" });
            var timeOutId = setTimeout(function () {
              $(".message").animate({ top: "-50px" });
              $(".message").css({
                display: "none",
              });
              timeOutId = "";
            }, 3000);
          } else {
            $(".download-range").css({
              display: "block",
              width: timeValue2 - timeValue1,
            });
          }
        }
      },
    });
  };
  // 时间转换
  $.adapterTime = function (time) {
    var arr,
      num = 0;
    arr = time.split(":");
    for (var index = 0; index < arr.length; index++) {
      if (arr[index] == "00") {
        num += 0;
      } else {
        if (index == 0) {
          num += Number(arr[0] * 60);
        }
        if (index == 1) {
          num += Number(arr[1]);
        }
        if (index == 2) {
          num += Number(Math.ceil(arr[2] / 60));
        }
      }
    }
    return num;
  };

  // 注册事件  拖拽
  $.drag = function (options, callback) {
    var draftingFlag = false,
      draftingFlagText = false;
    var isTrueArr = [],
      start1,
      end1;
    var draftingInner = false;
    var flagX = 16,
      sliderX = 0,
      ulX,
      downTimeSlideInnerOffsetLeft,
      timeFlagTextDrag = 0,
      flagTextDragOffsetEndLeft = 0;

    // 监听鼠标松开事件
    window.addEventListener("mouseup", function (e) {
      e.stopPropagation();
      draftingInner = false;
      draftingFlag = false;
      draftingFlagText = false;
      isDownloadRange = false;
      $(".time-slider-con").off("mousemove");
    });
    // 时间点拖动
    $(".time-flag").mousedown(function (event) {
      event.stopPropagation();
      var e = event || window.event;
      draftingFlag = true;
      timeFlagTextDrag = e.pageX;
      flagOffsetEndLeft = $(".time-flag")[0].offsetLeft;
    });

    $(".time-flag .text").mousedown(function (event) {
      event.stopPropagation();
      var e = event || window.event;
      draftingFlagText = true;
      timeFlagTextDrag = e.pageX;
      flagTextDragOffsetEndLeft = $(".time-flag")[0].offsetLeft;
      flagOffsetEndLeft = $(".time-flag")[0].offsetLeft;
    });

    $(".time-flag .text").mousemove(function (event) {
      event.stopPropagation();
      var e = event || window.event;
      isTrueArr = [];
      // 拖动时间文字逻辑
      if (draftingFlagText && !isdbClickDownloadRange) {
        flagX =
          e.pageX - timeFlagTextDrag + flagOffsetEndLeft >= flagOffsetBeginLeft
            ? e.pageX - timeFlagTextDrag + flagOffsetEndLeft
            : flagOffsetBeginLeft;

        if (flagX > timeSlideInnerWidthInit + timeSlideInnerLeft) {
          flagX = timeSlideInnerWidthInit + timeSlideInnerLeft;
        }

        $(".time-flag").css({ left: flagX });

        if (flagX > 63) {
          if ($(".time-slider-con").width() - flagX <= 63) {
            $("#text").css({
              left: -(63 + (70 - ($(".time-slider-con").width() - flagX))),
            });
          } else {
            $("#text").css({ left: -63 });
          }
        } else {
          $("#text").css({ left: -flagX });
        }

        for (var index = 0; index < options.videoTime.length; index++) {
          var element = options.videoTime[index];
          start1 = $.adapterTime(element.start);
          end1 = $.adapterTime(element.end);

          isTrueArr.push(
            start1 <= flagX - timeSlideInnerLeft + Math.abs(sliderX) &&
              flagX - timeSlideInnerLeft + Math.abs(sliderX) <= end1
          );
        }

        // 获取当前时间点的具体时间
        currentTime = $.zeroize(flagX - timeSlideInnerLeft + Math.abs(sliderX));
        $("#text").text(currentDate + "   " + currentTime);

        // 修改样式
        if (isTrueArr.indexOf(true) != -1) {
          $(".text").css({
            background: options.tipTextBackground || "#ff9a02",
          });
          $(".flag").css({
            background: options.tipTextBackground || "#ff9a02",
          });
          // 更新时间
          callback(currentTime);
        } else {
          $(".text").css({ background: "#d0d0d0" });
          $(".flag").css({ background: "#d0d0d0" });
        }
      }
    });
    $(".time-flag .text").mouseup(function (event) {
      event.stopPropagation();
      draftingFlagText = false;
    });

    // 时间轴拖动点击事件
    $(".time-slide-inner").mousedown(function (event) {
      event.stopPropagation();
      var e = event || window.event;
      draftingInner = true;
      isDownloadRange = true;
      downTimeSlideInnerOffsetLeft = $(".time-slide-inner")[0].offsetLeft - 16;
      flagOffsetEndLeft = $(".time-flag")[0].offsetLeft;
      downloadX = e.pageX;
      downloadRangeWidth = $(".download-range").width();
    });

    $(".time-slide-inner").mousemove(function (event) {
      event.stopPropagation();
      var e = event || window.event;
      isTrueArr = [];
      if ((draftingFlag || draftingInner) && !isdbClickDownloadRange) {
        // 拖动时间线逻辑
        if (draftingFlag) {
          flagX =
            e.pageX - timeFlagTextDrag + flagOffsetEndLeft >=
            flagOffsetBeginLeft
              ? e.pageX - timeFlagTextDrag + flagOffsetEndLeft
              : flagOffsetBeginLeft;
          $(".time-flag").css({ left: flagX });

          if (flagX > 63) {
            if ($(".time-slider-con").width() - flagX <= 63) {
              $("#text").css({
                left: -(63 + (70 - ($(".time-slider-con").width() - flagX))),
              });
            } else {
              $("#text").css({ left: -63 });
            }
          } else {
            $("#text").css({ left: -flagX });
          }
        }
        // 拖动时间轴逻辑
        if (draftingInner) {
          ulX = e.pageX - downloadX + downTimeSlideInnerOffsetLeft;
          if (ulX <= 0) {
            sliderX = e.pageX - downloadX + downTimeSlideInnerOffsetLeft;
          } else {
            sliderX = 0;
          }
          // console.log($(".time-slider-con").width() + Math.abs(sliderX));
          if (
            $(".time-slider-con").width() + Math.abs(sliderX) >=
            60 * 24 + 30
          ) {
            sliderX = $(".time-slider-con").width() - 60 * 24 - 30;
          }
          $(".time-slide-inner").css({ left: sliderX });
        }

        dataDate.flagEndWidth =
          Math.abs(sliderX) + (flagX - flagOffsetBeginLeft);

        // 修改样式
        for (var index = 0; index < options.videoTime.length; index++) {
          var element = options.videoTime[index];
          start1 = $.adapterTime(element.start);
          end1 = $.adapterTime(element.end);

          isTrueArr.push(
            start1 <= dataDate.flagEndWidth && dataDate.flagEndWidth <= end1
          );
        }

        // 获取当前时间点的具体时间
        currentTime = $.zeroize(dataDate.flagEndWidth);

        $("#text").text(currentDate + "   " + currentTime);
        // 修改样式
        if (isTrueArr.indexOf(true) != -1) {
          $(".text").css({
            background: options.tipTextBackground || "#ff9a02",
          });
          $(".flag").css({
            background: options.tipTextBackground || "#ff9a02",
          });
          // 更新时间
          callback(currentTime);
        } else {
          $(".text").css({ background: "#d0d0d0" });
          $(".flag").css({ background: "#d0d0d0" });
        }
      }

      // 拖动可下载区间逻辑
      if (isDownloadRange && isdbClickDownloadRange) {
        // downloadRangeWidth downloadRangeLeft
        var loadRangeX = e.pageX - downloadX + downloadRangeWidth;
        if (loadRangeX < 10) {
          loadRangeX = 10;
        }

        if (loadMax <= downloadRangeLeft + loadRangeX) {
          if (loadMax - downloadRangeLeft > 120) {
            $(".download-range").css({
              width: 120 + "px",
            });
            $("#datetimepicker_2").val(
              $.zeroize(downloadRangeLeft + 120) + ":00"
            );
            time2 = $.zeroize(downloadRangeLeft + 120) + ":00";
          } else {
            $(".download-range").css({
              width: loadMax - downloadRangeLeft + "px",
            });
            $("#datetimepicker_2").val($.zeroize(loadMax) + ":00");
            time2 = $.zeroize(loadMax) + ":00";
          }
        } else {
          if (loadRangeX > 120) {
            $(".download-range").css({ width: 120 + "px" });
            $("#datetimepicker_2").val(
              $.zeroize(downloadRangeLeft + 120) + ":00"
            );
            time2 = $.zeroize(downloadRangeLeft + 120) + ":00";
          } else {
            $(".download-range").css({ width: loadRangeX + "px" });
            $("#datetimepicker_2").val(
              $.zeroize(downloadRangeLeft + loadRangeX) + ":00"
            );
            time2 = $.zeroize(downloadRangeLeft + loadRangeX) + ":00";
          }
        }
      }
    });

    $(".time-slider-con").mouseup(function (event) {
      event.stopPropagation();
      draftingInner = false;
      isDownloadRange = false;
      draftingFlag = false;
      draftingFlagText = false;
    });
  };
  // 获取当前日期
  $.getNowFormatDate = function () {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  };

  $.zeroize = function (value) {
    var a = "",
      b = "",
      str1 = parseInt(value / 60) + "",
      str2 = parseInt(value % 60) + "";
    if (str1.length == 1) {
      a = "0" + parseInt(value / 60);
    } else {
      a = parseInt(value / 60) + "";
    }

    if (str2.length == 1) {
      b = "0" + parseInt(value % 60);
    } else {
      b = parseInt(value % 60) + "";
    }
    return a + ":" + b;
  };
});
